<template>
	<view class="login-wrapper">
		<view class="statusBar" :style="{
			height:`${statusBarHeight}px`,
		}"></view>
		<view :style="{
				height:`${statusBarHeight}px`,
			}"></view>
		<image src="/static/images/login/bg.png" :style="{
			top:`${statusBarHeight}px`,
		}" class="login-bg"></image>
		<view style="height:calc(50vw/3)"></view>
		<view class="pro-title">
			<image src="/static/images/login/logo.png" />
		</view>
		<view class="login-box">
			<view class="phone">
				<!-- 132******08 -->
			</view>
			<button class="btn" open-type="getPhoneNumber" @getphonenumber="submit">一键登录</button>
			<!-- <view class="bind">
				快捷绑定手机号
				<button 
				  open-type="getPhoneNumber"
				  @getphonenumber="handleGetPhoneNumber"
				  class="transparent-button"
				/>
			</view> -->
			
		</view>
		<u-toast ref="uToastRef"></u-toast>
	</view>
</template>

<script setup>
	import {
		getAesKey,
		aesDecrypt,
		aesEncrypt,
		DecryptNode,
		EncryptNode
	} from "../common/util/secret.js"
	import {
		getCurrentInstance
	} from "vue";
	import config from '@/common/config'
	const {
		proxy
	} = getCurrentInstance();

	const statusBarHeight = ref(0); // 状态栏高度（系统区域）
	const topHeight = ref(0); // 胶囊高度
	const pagePadding = ref(0);
	onMounted(() => {
		console.log('------------>', 2)
		const systemInfo = uni.getSystemInfoSync();
		statusBarHeight.value = systemInfo.statusBarHeight; // 获取状态栏高度

		const res = uni.getMenuButtonBoundingClientRect();
		pagePadding.value = systemInfo.screenWidth - res.right
		console.log(pagePadding.value)
		topHeight.value = res.height + (res.top - statusBarHeight.value) * 2
	});
	const btnLoading = ref(false);
	const uToastRef = ref();
	
	// getUserInfoByCookie
	
	const submit = async (e) => {
	    // 1. 处理用户授权结果
		console.log("获取phoneCode结果--->", e)
	    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
	      // 用户可能拒绝了授权
	      if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
	        uni.showToast({ title: '您已取消授权', icon: 'none' });
	      } else {
	        throw new Error(e.detail.errMsg);
	      }
	      return;
	    }
	    // 2. 获取临时凭证 phoneCode (用于后端换取手机号)
	    const phoneCode = e.detail.code;
		
		btnLoading.value = true;
		try {
		    // 1. 调用 uni.login 获取 code
		    const loginRes = await uni.login({
		      provider: 'weixin',
		      // onlyAuthorize: true // 可选：仅请求授权，不强制绑定手机号[4](@ref)
		    });
		
			console.log("获取openIdCode结果--->", loginRes)
		    if (loginRes.errMsg !== 'login:ok') {
		      throw new Error('手机账号登录失败: ' + loginRes.errMsg);
		    }
			const openIdCode = loginRes.code
			
			// 调用接口查询openId
			let openIdRes = await proxy.$http.POST('/wx-upms/wx/getUserOpen',{
				openCode: openIdCode,
			})
			console.log('openIdRes --->', openIdRes)
			const openId = openIdRes.openid
			
		    // 2. 将 code 发送给后端
			const sendData = {
				// loginNum: '18715157005',
				openIdCode: openId
				// phoneCode: phoneCode
			}
			
			var responseValue = await requestLogin(sendData)
			console.log('第一次登录结果:', responseValue);
			
		    // 3. 处理后端返回的数据
		    if (responseValue.success) { // true 表示成功, false表示失败
				const { token, userData } = responseValue.obj;
				// 存储 token 和用户信息
				uni.setStorageSync('token', token);
				uni.setStorageSync('userInfo', userData);
				uni.showToast({ title: '登录成功' });
				// 登录成功后的跳转逻辑...
				uni.reLaunch({
					url: "/pages/home"
				});
		    } else {
		      // 处理其他状态码，例如用户未注册 
		      // 可根据后端返回的特定状态码进行用户注册等操作
			    if (responseValue.errorCode == '10083') {
				  // 没有绑定的手机号
				    console.log('没有绑定的手机号!', responseValue);
					// todo 根据phoneCode查询手机号
					let phoneRes = await proxy.$http.POST('/wx-upms/wx/getUserPhone',{
						phoneCode: phoneCode,
					})
					console.log('phoneRes --->', phoneRes)
					const phone = phoneRes.phoneNumber
					
					const sendDataForBind = {
						loginNum: phone,
						openIdCode: openId
					}
					
					const phoneLoginRes = await requestLogin(sendDataForBind)
					console.log('携带手机号的登录结果:', phoneLoginRes);
					if (phoneLoginRes.success) { // true 表示成功, false表示失败
						const { token, userData } = phoneLoginRes.obj;
						// 存储 token 和用户信息
						uni.setStorageSync('token', token);
						uni.setStorageSync('userInfo', userData);
						uni.showToast({ title: '登录成功' });
						// 登录成功后的跳转逻辑...
						uni.reLaunch({
							url: "/pages/home"
						});
					} else {
						uni.showToast({ title: responseValue.errorMsg, icon: 'none' });
						console.log('手机号绑定失败:', phoneLoginRes);
					}
			    } else {
					uni.showToast({ title: responseValue.errorMsg, icon: 'none' });
					console.log('未知的接口返回值:', responseValue);
				}
		    }
		} catch (error) {
			console.error('登录过程出错:', error);
			uni.showToast({ title: '登录失败，请重试', icon: 'none' });
		} finally{
			btnLoading.value = false;
		}
	};
	const requestLogin = async (sendData) => {
		console.log('sendData--->',sendData)
		var dataStr = JSON.stringify(sendData)
		var key = getAesKey(16);
		var enParm = aesEncrypt(dataStr, key)
		var encodStr = EncryptNode(key)
		const response = await proxy.$http.POST('/aom/wechat/queryCommon',{
			obj:{
				data: enParm,
				secret: encodStr
			},
			url:'loginUserWithWxApp',
		})
		console.log('response ---->',response)
		//登录接口返回解密
		var responKey = DecryptNode(response.secret)
		var data = response.data
		if (!!response.data) {
			data = response.data.replace(/[\r\n]/g, "")
		}
		var responseValue = aesDecrypt(data, responKey)
		console.log('解码后的responseValue ----->',responseValue)
		return responseValue
	};
	// 获取手机号
	const handleGetPhoneNumber = async (e) => {
	  try {
		  console.log("获取phoneCode", e)
	    // 1. 处理用户授权结果
	    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
	      // 用户可能拒绝了授权
	      if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
	        uni.showToast({ title: '您已取消授权', icon: 'none' });
	      } else {
	        throw new Error(e.detail.errMsg);
	      }
	      return;
	    }
	    uni.showLoading({ title: '绑定中', mask: true });
	    // 2. 获取临时凭证 code (用于后端换取手机号)
	    const { code } = e.detail; // 注意：这里是从 e.detail 中获取 code
	
	    // 3. 将 code 发送给后端
		const bindRes = await proxy.$http.POST('send url',{
	        phoneCode: code // 将 code 发送给后端
	      })
	    // 4. 处理后端响应
	    if (bindRes.data.code === 200) {
	      uni.showToast({ title: '手机号绑定成功' });
	      // 更新本地用户信息等后续操作...
	    } else {
	      // 处理绑定失败的情况
	      uni.showToast({ title: bindRes.data.message || '绑定失败', icon: 'none' });
	    }
	  } catch (error) {
	    console.error('绑定手机号过程出错:', error);
	    uni.showToast({ title: '绑定失败，请重试', icon: 'none' });
	  } finally {
	    uni.hideLoading();
	  }
	};
</script>

<style scoped lang="scss">
	.login-wrapper {
		height: 100vh;
		position: relative;
		background-color: #f1f1f1;
		.login-bg {
			position: absolute;
			z-index: 0;
			left: 0;
			width: 100%;
		}

		.pro-title {
			display: flex;
			justify-content: center;
			margin-bottom: 80rpx;
			image {
				width: 332rpx;
				height: 89rpx;
				margin-right: 12rpx;
			}
		}

		.login-box{
			background-color: #fff;
			width: calc(100% - 40rpx);
			margin: auto;
			padding: 80rpx 40rpx;
			transform-style: preserve-3d;
			/* 在Z轴上移动 */
			transform: translateZ(1px);
			
			border-radius: 20rpx;
			
			display: flex;
			flex-direction: column;
			align-items: center;
		}
	}

	.btn{
		margin: 0;
		border-radius: 23px;
		background-color: $uni-color-project;
		color: #fff;
		width: 100%;
		margin-bottom: 40rpx;
	}
	.phone{
		font-size:60rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
	} 
	.bind{
		font-size:30rpx;
		color:$uni-color-project;
		cursor: pointer;
		position: relative;
		.transparent-button{
			position: absolute;
			top:0;
			left:0;
			width: 100%;
			height: 100%;
			opacity: 0;
			z-index: 10;
		}
	}
</style>